package cn.wwcyc.service.impl;

public class LinearRegression {
    private double[] x;
    private double[] y;
    private int n;
    private double slope;
    private double intercept;

    public LinearRegression(double[] x, double[] y) {
        if (x.length != y.length) {
            throw new IllegalArgumentException("The arrays x and y must have the same length.");
        }
        this.n = x.length;
        this.x = x;
        this.y = y;
        calculateCoefficients();
    }

    private void calculateCoefficients() {
        double xSum = 0.0, ySum = 0.0, xySum = 0.0, xxSum = 0.0;
        for(int i = 0; i < n; i++) {
            xSum += x[i];
            ySum += y[i];
            xySum += x[i] * y[i];
            xxSum += x[i] * x[i];
        }

        double denominator = n * xxSum - xSum * xSum;
        if(denominator == 0) {
            throw new ArithmeticException("Slope is undefined, denominator is zero.");
        }

        this.slope = (n * xySum - xSum * ySum) / denominator;
        this.intercept = (ySum - this.slope * xSum) / n;
    }

    public double getSlope() {
        return slope;
    }

    public double getIntercept() {
        return intercept;
    }

    public static void main(String[] args) {
        double[] xValues = {1, 2, 3, 4, 5};
        double[] yValues = {2, 3, 5, 7, 11}; // 示例数据点

        LinearRegression lr = new LinearRegression(xValues, yValues);
        System.out.println("Slope: " + lr.getSlope());
        System.out.println("Intercept: " + lr.getIntercept());
    }
}
